package com.weihua.modbus;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weihua.bo.MachineBo;
import com.weihua.bo.PlcBo;
import com.weihua.service.ModbusService;
import com.weihua.ws.MonitorServer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Administrator
 */
@Data
@Slf4j
public class ViewModal implements IView {

    private MachineBo param;

    private String sessionKey;

    private List<PlcBo> bos;

    Map<String, Object> result;
    ObjectMapper mapper = new ObjectMapper();
    @Override
    public void update() {
        if (this.getSessionKey()!=null && ModbusService.GLOBLE_DB_VIEW.equals(this.getSessionKey())){
            ModbusService.saveData(bos);
        }else{
            if (this.getResult()!=null){
                this.getResult().put("data", bos);
            }else{
                this.setResult(new HashMap<>());
                this.getResult().put("data", bos);
            }
            try {
                MonitorServer.sendAll(mapper.writeValueAsString(this.getResult()), this.getSessionKey());
            } catch (JsonProcessingException e) {
                log.warn(param.getIp()+"监控项出错：{}", e.getMessage());
            }
        }
    }
}
